<template>
  <el-dialog :title="'角色详情'" :visible.sync="_visible" :close-on-click-modal="closeOnClickModal" @open="_handleDialogOpen" @close="_cancel">
    <el-form ref="dataForm" :disabled="true" :model="form" :status-icon="true" :rules="formRules" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="角色名称：" prop="name">
            <span>{{ form.name }}</span>
          </el-form-item>
          <el-form-item label="备注：">
            <span>{{ form.remark }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="权限：" labe-position="top">
            <div class="detail-tree">
              <el-tree
                ref="elTreeRef"
                :is-loading="functionLoading"
                :data="functionTree"
                :props="functionProps"
                :default-expand-all="functionExpandAll"
                :default-checked-keys="form.functionIdList"
                node-key="id"
                empty-text="暂无数据"
                highlight-current
                show-checkbox
                @check-change="functionCheckChange" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <!-- <el-button size="small" @click="_cancel">取 消</el-button> -->
      <el-button :loading="_loading" size="small" type="primary" @click="_cancel">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>

// import waves from '@/directive/waves' // Waves directive
import { mapGetters } from 'vuex'
// import dicData from './dic-data'
import { getRoleDeatilById } from '@/api/systemManage/role'
import { getUserFunctionTree } from '@/api/systemManage/function'

export default {

  props: {
    closeOnClickModal: {
      type: Boolean,
      default: false
    },

    visible: {
      type: Boolean,
      default: false
    },

    loading: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      isEdit: false,

      form: {},
      formRules: {},

      functionLoading: false,
      functionTree: [],
      functionProps: {
        label: 'sysName'
      },
      functionIsCheckAll: false,
      functionExpandAll: false
    }
  },

  computed: {

    ...mapGetters([
      'lang',
      'userId'
    ]),

    '_visible': {
      get() {
        return this.visible
      },

      set(value) {
        this.$emit('update:visible', value)
      }
    },
    '_loading': {
      get() {
        return this.loading
      },

      set(value) {
        this.$emit('update:loading', value)
      }
    }
  },

  methods: {
    _handleDialogOpen() {
      this.getFunction()
      // this.formReset()
      this.$emit('open')
    },

    _cancel() {
      this.formReset()
      this._visible = false
      this.isLoading = false
      this.$emit('cancel')
    },

    _ok() {
      const form = this.$refs['dataForm']
      form.validate(valid => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(this.form))
          this.$emit('ok', formData, this.isEdit)
        }
      })
    },

    show(params) {
      this._visible = true
      this.isEdit = false
      if (params) {
        getRoleDeatilById(params.id || params).then(resp => {
          this.form = resp.data
          // if (this.form.type && typeof this.form.type === 'string') {
          //   this.form.type = this.form.type.split(',')
          // }
        }).catch(resp => {
          this.$message.error(resp.message)
        })
      }
    },

    close() {
      this._cancel()
    },

    formReset() {
      this.form = {
        name: '',
        roleCode: '',
        remark: '',
        functionIdList: []
      }
      this.$nextTick(() => {
        this.$refs.dataForm.resetFields()
      })
    },

    getFunction() {
      this.functionLoading = true
      getUserFunctionTree({ userId: this.userId }).then(res => {
        this.functionLoading = false
        if (res.code === 200) {
          this.functionTree = res.data
        } else this.$message.error(res.message)
      }).catch(e => {
        this.functionLoading = false
        this.$message.error(e.message)
      })
    },

    functionCheckSet(type) {
      this.functionIsCheckAll = type !== undefined ? type : !this.functionIsCheckAll
      if (this.functionIsCheckAll) {
        const keys = this.getFunctionAllKey(this.functionTree)
        this.$refs.elTreeRef.setCheckedKeys(keys)
      } else {
        this.$refs.elTreeRef.setCheckedKeys([])
      }
    },

    getFunctionAllKey(nodes) {
      const arr = []
      for (let i = 0; i < nodes.length; i++) {
        arr.push(nodes[i].id)
        if (Array.isArray(nodes[i].children) && nodes[i].children.length) {
          arr.push(...this.getFunctionAllKey(nodes[i].children))
        }
      }
      return arr
    },

    functionCheckChange() {
      const keys = this.$refs.elTreeRef.getCheckedKeys()
      this.form.functionIdList = keys
      this.$forceUpdate()
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-tree {
  padding-top: 10px;
}
</style>

